package org.wuhong.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName TestCommunicaitonServer
 * @Description TODO
 * @Author director吴
 * @Date 2022/1/4 13:10
 * @Version 1.0
 **/
public class TestCommunicaitonServer {

    public static void main(String[] args) throws Exception {


        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        Selector selector = Selector.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(6666));

        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true){
            if (selector.select(1000) == 0){
                System.out.println("等待一秒钟，无连接");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            //iterator.hasNext()
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if (key.isAcceptable()){
                    System.out.println("有新的客户端连接");
                    SocketChannel channel = serverSocketChannel.accept();
                    channel.configureBlocking(false);
                    System.out.println("channel序列号："+channel.hashCode());
                    channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }


                if (key.isReadable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("客户端："+ new String(buffer.toString()));
                }
                iterator.remove();
            }


        }
















    }
}
